<template>
    <el-dialog
        class="config_template_dialog"
        :title="title"
        :model-value="props.modelValue"
        width="80%"
        @close="handleVisible()">
        <div class="select-keyword">
            <div class="select-keyword-left">
                <el-form ref="formRef" label-position="top" :rules="rules" :model="tplInfo" @submit.prevent>
                    <el-form-item label="消息模板" prop="title">
                        <el-select v-model="tplInfo.tid" @change="handleChange">
                            <el-option
                                v-for="item in templateList"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="keywordList" label="消息内容">
                        <el-dropdown trigger="click" class="el-dropdown-dropdown">
                            <span class="el-dropdown-link">
                                <el-icon><Plus /></el-icon>
                                插入动态参数
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item
                                        v-for="{ name, key } in dynamicParams"
                                        :key="key"
                                        @click="handleAdd(name)"
                                        >{{ name }}</el-dropdown-item
                                    >
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <div class="params-box">
                            <div v-if="keywordLen <= 0" class="no-data">请选择消息模板</div>
                            <div v-else class="has-data">
                                <div v-for="(item, index) in tplInfo.keywordList" :key="item.kid">
                                    <span>{{ item.name }}</span>
                                    <el-form-item :prop="'keywordList.' + index + '.valueTpl'" :rules="paramsRule">
                                        <el-input v-model="item.valueTpl" @click="getInput($event, item)"></el-input>
                                    </el-form-item>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="select-keyword-right">
                <div class="select-keyword-right-title">
                    <img src="@/assets/imgs/sys/wechat-dark-icon.png" style="width: 16px; margin-right: 6px" alt="" />
                    小程序名称
                </div>
                <div class="select-keyword-right-scroll">
                    <!-- todo:模板title -->
                    <h5>{{ tplInfo.title }}</h5>
                    <div v-for="{ kid, name, valueTpl } in tplInfo.keywordList" :key="kid">
                        <span>{{ name }}</span
                        ><span v-html="valueTpl"></span>
                    </div>
                </div>
                <div class="select-keyword-right-view">
                    查看详情
                    <el-icon><ArrowRight /></el-icon>
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleVisible()">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { reactive, ref, unref, computed, watch } from 'vue';
import request from '@/request/index';
import { cursorPosition, insertInputTxt, cloneDeep } from '@/commons/utils';
import { ElMessage } from 'element-plus';

const props = defineProps({
    modelValue: Boolean,
    query: Object
});

const emit = defineEmits(['update:modelValue']);

const formRef = ref();
let templateList = reactive([]);
const clickedInput = reactive({});
const dynamicParams = reactive([]);
const tplInfo = reactive({
    title: null,
    tid: null,
    keywordList: null
});
let currentItem = reactive({});
const checkParams = () => {};
const rules = reactive({
    title: [{ required: true, trigger: 'change', message: '请选择消息模板' }],
    keywordList: [{ required: true, trigger: 'change', message: '未选择消息内容' }]
});
const paramsRule = [{ required: true, trigger: 'change', message: '此字段必填' }];

const title = computed(() => {
    return `配置${props.query.msgNameZh}`;
});
const keywordLen = computed(() => {
    return tplInfo?.keywordList?.length || 0;
});

const getInput = (el, item) => {
    currentItem = item;
    Object.assign(clickedInput, cursorPosition(el.target));
};

const handleChange = async val => {
    // const target = templateList.find(item => item.id === val);
    // const { data } = await request('miniappMsgTplKeywords', {
    //     tid: target?.id,
    //     categoryId: 0,
    //     flush: 1
    // });
    const target = templateList.find(item => item.id === val);
    tplInfo.title = target?.title || '';
    tplInfo.tid = target?.id || '';
    tplInfo.keywordList = cloneDeep(target?.keywordList);
};

const handleAdd = name => {
    if (!tplInfo.title) {
        ElMessage({
            type: 'error',
            message: '请先选择消息模板'
        });
        return;
    }
    if (!clickedInput.elInput) {
        ElMessage({
            type: 'error',
            message: '没有点击过输入框，请先点击输入框插入的位置'
        });
        return;
    }
    currentItem.valueTpl = insertInputTxt(clickedInput, `{${name}}`);
};

watch(
    () => props.modelValue,
    val => {
        if (val) {
            // 获取接口
            getAllData();
            formRef.value && formRef.value.clearValidate('title');
        } else {
            // 重置
            const tpl = cloneDeep(props?.query?.tplList?.[0]?.tplInfo || {});
            tpl.keywordList = [];
            tpl.tid = '';
            tpl.title = '';
            // tpl.keywordList &&
            //     (tpl.keywordList = tpl?.keywordList?.map(item => {
            //         item.valueTpl = item.valueTplCn || item.valueTpl;
            //         return item;
            //     }));
            Object.assign(tplInfo, tpl);
            formRef.value && formRef.value.clearValidate('title');
        }
    }
);
watch(
    () => props.query,
    val => {
        const tpl = cloneDeep(val.tplList?.[0]?.tplInfo || {});
        tpl.keywordList &&
            (tpl.keywordList = tpl?.keywordList?.map(item => {
                item.valueTpl = item.valueTplCn || item.valueTpl;
                return item;
            }));
        Object.assign(tplInfo, tpl);
    },
    {
        deep: true
    }
);

const handleVisible = (visible = false) => {
    emit('update:modelValue', visible);
};

const handleConfirm = async () => {
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            const tpl = cloneDeep(tplInfo);
            tpl.keywordList = tpl.keywordList.map(item => {
                item.valueKeys = dynamicParams.flatMap(fItem => {
                    if (item.valueTpl.includes(`{${fItem.name}}`)) {
                        return [fItem.key];
                    }
                    return [];
                });
                item.valueTplCn = item.valueTpl;
                dynamicParams.forEach(fItem => {
                    item.valueTpl = item.valueTpl.replace(`{${fItem.name}}`, `{${fItem.key}}`);
                });
                return item;
            });
            await request('miniappBuyerMsgListUpdate', {
                id: props.query.id,
                tplInfo: tpl
            });
            handleVisible(false);
            emit('handle-refresh');
        }
    });
};

const getTemplate = async () => {
    const res = await request('miniappMsgTplList');
    const list = res.data.list || [];
    templateList.length = 0;
    Object.assign(templateList, list);
};

const getDynamicParams = async () => {
    const { type, msgName } = props.query;
    const { data } = await request('miniappBuyerMsgListDynamic', {
        type,
        msgName
    });
    dynamicParams.length = 0;
    Object.assign(dynamicParams, data.list || []);
};

const getAllData = () => {
    getTemplate();
    getDynamicParams();
};
</script>
<style lang="scss">
.config_template_dialog {
    max-width: 1000px;
    min-width: 800px;
}
</style>
<style lang="scss" scoped>
%scroll {
    &::-webkit-scrollbar {
        width: 5px;
        height: 40px;
    }
    &::-webkit-scrollbar-track {
        background: #fff;
        border-radius: 3px;
    }
    &::-webkit-scrollbar-thumb {
        background: #d8d8d8;
        border-radius: 3px;
    }
    &::-webkit-scrollbar-thumb:hover {
        background: #333;
    }
    &::-webkit-scrollbar-corner {
        background: #179a16;
    }
}
.config_template_dialog {
    .select-keyword {
        display: flex;
        justify-content: space-between;
        &-left {
            flex: 1;
            margin-right: 64px;
        }
        &-right {
            flex: 1;
            max-width: 364px;
            min-width: 280px;
            height: 336px;
            background: #ffffff;
            border: 1px solid #eaeaea;
            display: flex;
            flex-direction: column;
            &-title {
                padding-left: 24px;
                display: flex;
                align-items: center;
                height: 56px;
                font-size: 16px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
            }
            &-scroll {
                flex: 1;
                overflow-y: auto;
                border-top: 1px solid #eaeaea;
                border-bottom: 1px solid #eaeaea;
                padding: 16px 24px;
                @extend %scroll;
                h5 {
                    font-size: 14px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    color: #33302d;
                    margin: 0;
                    margin-bottom: 16px;
                }
                & > div {
                    margin-bottom: 16px;
                    display: flex;
                    justify-content: space-between;
                    align-items: flex-start;
                    span {
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #969696;
                        &:last-of-type {
                            color: #33302d;
                            margin-left: 8px;
                            word-break: break-all;
                            max-width: 200px;
                        }
                    }
                }
            }
            &-view {
                display: flex;
                justify-content: space-between;
                padding: 0 24px;
                align-items: center;
                height: 48px;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #969696;
            }
        }
    }

    .params-label {
        display: inline-flex;
        justify-content: space-between;
        align-items: center;
        width: calc(100% - 15px);
    }

    .params-box {
        width: 100%;
        height: 224px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #eaeaea;
        overflow: hidden;
        overflow-y: auto;
        @extend %scroll;
    }

    .no-data {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .has-data {
        padding: 24px 5px;
        width: 100%;
        height: auto;

        & > div {
            display: flex;
            margin-bottom: 16px;
            width: 100%;
            & > span {
                display: inline-block;
                width: 110px;
                text-align: right;
                word-break: break-all;
                padding-right: 10px;
            }
            :deep(.el-form-item) {
                width: calc(100% - 180px);
            }
        }
    }
    .el-dropdown-dropdown {
        position: absolute;
        top: -28px;
        right: 0;
    }

    .el-dropdown-link {
        cursor: default;
        display: flex;
        align-items: center;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ff6b00;
        i {
            margin-right: 4px;
        }
    }
}
</style>
